<template>
  <div class="dialog">
    <el-form ref="result" :model="result" :rules="formrules">
      <el-tabs v-model="active">
        <!-- 基本信息配置界面 -->
        <el-tab-pane label="基本信息">
          <el-form-item v-for="(item,key) in displayTemplateItem" :key="key" label-width="10rem" :label="item.name" :prop="key">
            <el-switch v-if="item.bool" v-model="result[item.bindkey]" :readonly="item.readonly" />
            <el-input v-else-if="item.text" v-model="result[item.bindkey]" :readonly="item.readonly" auto-complete="off" />
            <el-select v-else-if="item.list" v-model="result[item.bindkey]" :readonly="item.readonly" placeholder="请选择">
              <el-option v-for="option in options[result.category_uid]" :key="option.uid" :value="option.uid" :label="option.name" />
            </el-select>
            <span v-else>{{ item }}</span>
          </el-form-item>
        </el-tab-pane>
        <!-- 属性信息配置界面 -->
        <el-tab-pane label="属性信息">
          <el-form-item v-for="item in result.infolist" :key="item.uid" label-width="10rem" :label="item.info_name" :prop="item.uid">
            <el-upload
              v-if="display[item.info_id] && display[item.info_id].file"
              ref="upload"
              class="upload-demo"
              action=""
              :limit="1"
              :on-exceed="handleExceed"
              :on-change="(file,filelist) => handleChange(file,filelist,item)"
              :on-remove="(file,filelist) => handleRemove(file,filelist,item)"
              :file-list="item.value ? [{name: item.value, url: item.value}] : []"
              :readonly="display[item.info_id] && display[item.info_id].readonly"
              :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
            <el-select v-else-if="item.infoset && item.infoset!==null" v-model="item.infoset_uid" :readonly="display[item.info_id] && display[item.info_id].readonly" placeholder="请选择">
              <el-option v-for="option in item.infoset" :key="option.uid" :value="option.uid" :label="option.name" />
            </el-select>
            <el-input v-else v-model="item.value" :readonly="display[item.info_id] && display[item.info_id].readonly" auto-complete="off" />
          </el-form-item>
        </el-tab-pane>
        <!-- 关联信息配置界面 -->
        <el-tab-pane label="关联信息">
          <el-form-item v-for="temp in displayTemplateRelation" :key="temp.uid" label-width="10rem" :label="temp.name" :prop="temp.uid">
            <el-select v-for="item in result.relation ? result.relation.filter(val => val.relation_uid && val.relation_uid === temp.relation_uid) : []" :key="item.uid" v-model="item.target_uid" placeholder="请选择" class="relationselect">
              <el-option v-for="option in options[temp.target_uid]" :key="option.uid" :value="option.uid" :label="option.name" />
            </el-select>
            <el-button @click="addRelation(temp)">添 加</el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="Number(active)===2 ? false :true" @click="submit('result',result, filedata)">确 定</el-button>
      <el-button @click="next">下一步</el-button>
      <el-button type="primary" @click="cancel('result', $event)">取 消</el-button>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'EditCiModel',
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    template: {
      type: Object,
      required: true,
      default: () => {}
    }
  },
  data() {
    return {
      active: '0',
      defaultinput: '---请输入---',
      defaultoptionorganiz: { organiz_id: null, organiz_name: '---请选择---' },
      options: {},
      result: {},
      filedata: {},
      formrules: {
        name: [
          { required: true, message: '请输入名称' }
        ],
        id: [
          { required: true, message: '请输入身份标识' }
        ],
        value: [
          { required: true, message: '请输入属性值' }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      display: state => state.systemProfile.display,
      service: state => state.service
    }),
    displayTemplateRelation() {
      return this.template.relation.filter(item => item.origin_uid === this.template.uid)
    },
    displayTemplateItem() {
      const keys = Object.keys(this.template)
      return keys.reduce((result, key) => (
        this.display[key] && this.display[key].show
          ? { ...result, [key]: this.display[key] }
          : result), {})
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      // this.$refs['result'].resetFields();
      await this.getResult()
      await this.getOptions()
    },
    getResult() {
      this.result = {
        category_uid: this.template.uid,
        ...this.data,
        relation: [],
        infolist: [],
        remove_info: []
      }
      if (this.result.infolist && this.result.infolist !== null && this.data.infolist && this.data.infolist !== null && this.template.infolist && this.template.infolist !== null) {
        this.data.infolist.map(item => { this.result.infolist.push({ ...item }) })
        this.template.infolist.map(item => {
          if (!this.data.infolist.find(val => val.info_uid === item.info_uid)) {
            this.result.infolist.push({ ...item })
          }
        })
      } else {
        this.template.infolist.map(item => { this.result.infolist.push({ ...item }) })
      }
      if (this.data.relation && this.data.relation !== null && this.template.relation && this.template.relation !== null) {
        this.data.relation.map(item => { this.result.relation.push({ ...item }) })
      }
    },
    async getOptions() {
      // 获取下拉列表
      let result = await this.service.getCi({ category_uid: this.result.category_uid })
      if (result.flag && result.data) {
        this.options = { ...this.options, [this.result.category_uid]: result.data }
      }
      for (const item of this.template.relation) {
        result = await this.service.getCi({ category_uid: item.target_uid })
        if (result.flag && result.data) {
          this.options = { ...this.options, [item.target_uid]: result.data }
        }
      }
    },
    addRelation(temp) {
      this.result.relation.push({ relation_uid: temp.relation_uid, target_uid: null })
    },
    submit(form, data, filedata) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.$emit('submit', data, filedata)
          // console.log('datacimodel', data, filedata)
        } else {
          this.$message.error('请按要求填写！')
          return false
        }
      })
    },
    cancel(form, $event) {
      // 重置表单内容
      this.$refs[form].resetFields()
      this.$emit('cancel', $event)
    },
    // 上传图片
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`)
    },
    handleChange(files, fileList, item) {
      this.filedata[item.uid] = fileList && fileList.length > 0 ? fileList[0].raw : null
    },
    handleRemove(files, fileList, item) {
      this.result.remove_info.push({ ...item })
    },
    next() {
      let active = Number(this.active)
      if (active++ > 1) {
        this.active = '0'
      } else {
        this.active = active.toString()
      }
    }
  }
}
</script>
